package com.example.shiro.realm;

import com.example.shiro.utils.UserAuthInfo;
import com.example.sys.org.model.SysOrgUser;
import com.example.sys.org.service.SysOrgUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ShiroRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysOrgUserService sysOrgUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserAuthInfo userAuthInfo = (UserAuthInfo) principalCollection.getPrimaryPrincipal();
        authorizationInfo.setRoles(userAuthInfo.getAuthRoleAliases());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        UserAuthInfo userAuthInfo = this.sysOrgUserService.loadUserByUserName(username);
        if (userAuthInfo == null) {
            throw new UnknownAccountException("用户名或密码不正确");
        }
        SysOrgUser sysOrgUser = userAuthInfo.getSysOrgUser();
        if (!password.equals(sysOrgUser.getFdPassWord())) {
            throw new IncorrectCredentialsException("用户名或密码不正确");
        }
        return new SimpleAuthenticationInfo(userAuthInfo, password, getName());
    }
}
